package com.example.volunteeroa.controller;

import com.example.volunteeroa.entity.*;
import com.example.volunteeroa.repository.*;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;


@CrossOrigin//跨域
@RestController
@RequestMapping("api/user")
public class UserController {
    @Resource
    UserRepository URepository;

    @PostMapping("login")
    public RestBean login(@RequestBody Users users) {
        String name = users.getUserName();
        String psw = users.getPassWord();
        Optional<Users> usersByUserName = URepository.findUsersByUserName(name);
        if (usersByUserName.isPresent()) {
            if (usersByUserName.get().getPassWord().equals(psw)) {
                return new RestBean(200, "登录成功", new LoginRes(name, usersByUserName.get().getRole(), usersByUserName.get().getManageID()));
            }

        } else {
            return new RestBean(500, "登陆失败，请检查用户名或密码", null);
        }
        return new RestBean(500, "登陆失败，请检查用户名或密码", null);

    }

    @GetMapping()
    public RestBean findAll() {
        List<Users> all = URepository.findAll();
        return new RestBean(200, "查询全部成功", all);
    }

    @PutMapping()
    public RestBean update(@RequestBody Users users) {
        URepository.save(users);
        return new RestBean(200, "更新成功", null);
    }

    @PostMapping()
    public RestBean add(@RequestBody Users users) {
        URepository.save(users);
        return new RestBean(200, "添加成功", null);
    }


    @DeleteMapping()
    public RestBean delete(@RequestBody Users users) {
        URepository.deleteById(users.getUserID());
        return new RestBean(200, "删除成功", null);
    }
}